import React from 'react';
import { Button, Form, Input, message } from 'antd';
import { useState, useEffect } from 'react';
import './login.css'

import { useDispatch, useSelector } from 'react-redux';
// 更新到redux
import { updateUser, updateLogin, updateForgot, updateRegister } from '../store/userSlice';
// 消息提示

const Login = () => {
    const [messageApi, contextHolder] = message.useMessage();

    const dispatch = useDispatch();
    const user = useSelector(state => state.user);
    // console.log(user.user);
    const handleClick = () => {
        dispatch(updateUser({
            username: 'admin',
            email: '289'
        }));
    };
    const [status, setStatus] = useState('login');
    const clickLogin = function () {
        setStatus('login')
    }
    //点击了忘记密码
    const clickRorgot = function () {
        setStatus('forgot')
        // console.log(status);
    }
    const clickRegister = function () {
        setStatus('register')
    }
    const [form] = Form.useForm();
    // console.log(form);
    const [isPhoneValid, setIsPhoneValid] = useState(false);
    // 验证用户名
    const validateUsername = (_, value) => {
        if (!value) {
            return Promise.reject(new Error('用户名是必填项'));
        }
        if (value.length > 6) {
            return Promise.reject(new Error('用户名不能超过6位'));
        }
        if (!/^[a-zA-Z0-9]+$/.test(value)) {
            return Promise.reject(new Error('用户名只能包含字母和数字'));
        }
        return Promise.resolve();
    };
    // 验证密码
    const validatePassword = (_, value) => {
        if (!value) {
            return Promise.reject(new Error('密码是必填项'));
        }
        if (value.length < 6) {
            return Promise.reject(new Error('密码至少6位'));
        }
        if (!/[A-Z]/.test(value)) {
            return Promise.reject(new Error('密码至少包含一个大写字母'));
        }
        if (!/[a-z]/.test(value)) {
            return Promise.reject(new Error('密码至少包含一个小写字母'));
        }
        if (!/[0-9]/.test(value)) {
            return Promise.reject(new Error('密码至少包含一个数字'));
        }
        if (!/[!@#$%^&*]/.test(value)) {
            return Promise.reject(new Error('密码至少包含一个特殊字符'));
        }
        return Promise.resolve();
    };
    // 验证手机号
    const validatePhone = (_, value) => {
        if (!value) {
            return Promise.reject(new Error('手机号是必填项'));
        }
        if (value.length != 11) {
            return Promise.reject(new Error('手机号长度为11位'));
        }
        if (!/^1[3456789]\d{9}$/.test(value)) {
            return Promise.reject(new Error('手机号格式不正确'));
        }
        return Promise.resolve();
    };
    // 验证验证码
    const validateQrCode = (_, value) => {
        if (!value) {
            return Promise.reject(new Error('验证码是必填项1'));
        }
        if (value.length != 6) {
            return Promise.reject(new Error('验证码长度为6位'));
        }
        if (!/^[0-9]+$/.test(value)) {
            return Promise.reject(new Error('验证码只能包含数字'));
        }
        return Promise.resolve();
    };
    //登录提交操作
    const LoginSubmitForm = function (values) {
        dispatch(updateLogin(values));
        localStorage.setItem('login_info', JSON.stringify(values));
        messageApi.open({
            type: 'success',
            content: '登录成功,信息保存成功',
        });
    }
    // 注册提交操作
    const RegisterSubmitForm = function (values) {
        dispatch(updateRegister(values));
        localStorage.setItem('register_ingo', JSON.stringify(values));
        messageApi.open({
            type: 'success',
            content: '注册成功,信息保存成功',
        });
    }
    // 找回密码提交操作
    const ForgotSubmitForm = function (values) {
        dispatch(updateRegister(values));
        localStorage.setItem('register_ingo', JSON.stringify(values));
        messageApi.open({
            type: 'success',
            content: '信息找回成功,信息保存成功',
        });
    }
    //注册得验证码
    const [qr_register_status, set_qr_register_status] = useState('获取验证码');
    const [qr_forgot_status, set_qr_forgot_status] = useState('获取验证码');
    // 注册的手机号 没有手机号不能获取验证码
    const [register_phone, set_register_phone] = useState('');
    // let register_phone = ''
    const register_phone_change = async (e) => {
        try {
            // 验证手机号码是否输入
            let res = await form.validateFields(['phoneNumber']);
            console.log(res);
            if (res) {
                setIsPhoneValid(true)
            }
        } catch (errorInfo) {
            console.log('验证失败:', errorInfo);
            setIsPhoneValid(false)
        }
    }

    const get_qr_code = async () => {
        // 验证手机号码
        let res = await form.validateFields(['phoneNumber']);
        if (res) {
            // 开始倒计时
            set_qr_register_status(30);
        } else {
            console.log('手机号不对');
        }
    }

    // 获取找回密码得qrCode
    const get_qr_forgot_code = async () => {
        // 验证手机号码
        let res = await form.validateFields(['phoneNumber']);
        if (res) {
            // 开始倒计时
            set_qr_forgot_status(30);
        } else {
            console.log('手机号不对');
        }
    }

    useEffect(() => {

        if (qr_forgot_status >= 0) {
            const timer = setTimeout(() => {
                set_qr_forgot_status(qr_forgot_status - 1);
            }, 1000);
            return () => clearTimeout(timer);
        } else {
            set_qr_forgot_status('获取验证码')
        }


    }, [qr_forgot_status]);

    useEffect(() => {
        if (qr_register_status >= 0) {
            const timer = setTimeout(() => {
                set_qr_register_status(qr_register_status - 1);
            }, 1000);
            return () => clearTimeout(timer);
        } else {
            set_qr_register_status('获取验证码')
        }



    }, [qr_register_status]);


    function LoginForm() {
        return (

            <div class="login-form">
                <h3>登录</h3>
                <Form
                    form={form}
                    style={{ minWidth: 300, width: 300 }}
                    onFinish={LoginSubmitForm}
                >
                    <Form.Item
                        name={'username'}
                        rules={
                            [{
                                validator: validateUsername
                            }]
                        }>
                        <Input placeholder='请输入用户名' style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ validator: validatePassword }]}
                    >
                        <Input.Password placeholder='请输入密码' style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item >
                        <button id="loginForm_loginButton" type="submit">登录</button>
                    </Form.Item>
                </Form>
                <div class="login-other-button">
                    <div style={{ color: '#9995F9' }} onClick={clickRorgot}>
                        忘记密码
                    </div>
                    <div onClick={clickRegister} >
                        没有账号?
                        <span style={{ color: '#9995F9',paddingLeft:'5px' }}>快速注册</span>
                    </div>

                </div>
            </div>
        )
    }

    function RegisterForm() {
        return (
            <div class="login-form">
                <h3>用户注册</h3>
                <Form
                    form={form}
                    onFinish={RegisterSubmitForm}
                    style={{ minWidth: 300, width: 300 }}
                >
                    <Form.Item
                        name="username"
                        rules={[{ validator: validateUsername }]}
                    >
                        <Input placeholder='请输入用户名' style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item
                        name="phoneNumber"
                        rules={[{ validator: validatePhone }]}
                    >
                        <Input placeholder='请输入手机号'
                            // value={register_phone}
                            onChange={register_phone_change}
                            style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item
                        name="verificationCode"
                        rules={[
                            {
                                required: true,
                                message: '请输入验证码',
                            },
                            {
                                pattern: /^\d{6}$/,
                                message: '验证码必须为六位数字',
                            },
                        ]}
                        className="qrcode_item">
                        <div>
                            <Input placeholder='请输入验证码' style={{ borderRadius: 0, width: 180 }} />

                            <Button className='qrcode_button' type="primary"
                                disabled={!isPhoneValid}
                                onClick={(e) => {
                                    e.preventDefault();
                                    get_qr_code();
                                }} style={{ width: '104px' }}>{qr_register_status}</Button>
                        </div>
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ validator: validatePassword }]}
                    >
                        <Input.Password placeholder='请输入密码' style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                        {/* <button id="loginForm_loginButton" type="submit" >立即注册</button> */}
                        {/* <div class="login_Button" htmlType="submit" >立即注册</div> */}
                    </Form.Item>
                </Form>
                <div class="login-other-button" >
                    <div style={{ color: '#9995F9' }} onClick={clickRorgot}>
                        忘记密码
                    </div>
                    <div>
                        已有账号?
                        <span style={{ color: '#9995F9', paddingLeft: '5px' }} onClick={clickLogin}>马上登录</span>
                    </div>

                </div>
            </div>
        )
    }

    // 忘记密码的表单
    function ForgotForm() {
        return (
            <div class="login-form">
                <h3>找回密码</h3>
                <Form
                    form={form}
                    onFinish={ForgotSubmitForm}
                    style={{ minWidth: 300, width: 300 }}
                >
                    <Form.Item
                        name="phoneNumber"
                        rules={[{ validator: validatePhone }]}
                    >
                        <Input placeholder='请输入手机号'
                            onChange={register_phone_change}
                            style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item
                        name="newPassword"
                        rules={[{ validator: validatePassword }]}
                    >
                        <Input.Password placeholder='请输入新密码' style={{ borderRadius: 0 }} />
                    </Form.Item>
                    <Form.Item
                        name="qrcode"
                        rules={[{ validator: validateQrCode }]}
                        className="qrcode_item">
                            
                        <div> 
                            <Input placeholder='请输入验证码' style={{ borderRadius: 0, width: 180 }} />
                            <Button className='qrcode_button' type="primary"
                                disabled={!isPhoneValid}
                                onClick={(e) => {
                                    e.preventDefault();
                                    get_qr_forgot_code();
                                }} style={{ width: '104px' }}>{qr_forgot_status}</Button>
                        </div>
                    </Form.Item>

                    <Form.Item>
                        <button id="loginForm_loginButton" type="submit">登录</button>
                        {/* <div class="login_Button" htmlType="submit">登录</div> */}
                    </Form.Item>
                </Form>
                <div class="login-other-button">
                    <div style={{ color: '#9995F9' }} onClick={clickLogin}>
                        立刻登录
                    </div>
                    <div>
                        没有账号?
                        <span style={{ color: '#9995F9', paddingLeft: '5px' }} onClick={clickRegister}>快速注册</span>
                    </div>

                </div>
            </div>
        )
    }

    return (
        <>
            <>
                {contextHolder}
                <div className="login">
                    {/* if(status == 'login' ){
                        return <LoginForm />
                    } */}
                    {status == 'login' && <LoginForm />}
                    {status == 'forgot' && <ForgotForm />}
                    {status == 'register' && <RegisterForm />}

                </div>
            </>
        </>
    );
};

export default Login;
